/**
 * Created by cuppi on 2017/6/29.
 */

var AipFace = require('../lib/AIFace/AipFace')
var fs = require('fs');
var path = require('path');
var qiniu = require('qiniu');
var NetworkManager = require('../network/NetworkManager');
var ImageTool = require('../tool/ImageTool');
const defaultDevelop = 'develop';

let _instance;
let _faceClint;
class FaceManager {

    constructor() {
        _faceClint = new AipFace('9824949', 'vzNueiH5OsaqhPXGqQtgD2N7', 'NhdT6xGB3iZ2pQsncZOw6kuKSm9wT6hv');
    }

    static defaultManager() {
        if (!_instance) {
            _instance = new FaceManager();
        }
        return _instance;
    }

    /**
     * 通过图片链接提取用户脸型特征
     * @param imageUrl 用户人脸url
     * @returns {Promise}
     */
    detectUserFromUrl(imageUrl){
        return new Promise((resolve, reject) => {
            NetworkManager.getBase64Image(imageUrl).then(base64Img => {
                _faceClint.detect(base64Img).then(data => {
                    resolve(data);
                }, error => {
                    reject(error);
                })
            }, error => {
                reject(error);
            });
        })
    }

    /**
     * 通过图片提取用户脸型特征
     * @param image 用户人脸图片
     * @returns {Promise}
     */
    detectUserFromImage(image){
        return new Promise((resolve, reject) => {
            let base64Img = ImageTool.base64FromImageData(image);
            _faceClint.detect(base64Img).then(data => {
                resolve(data);
            }, error => {
                reject(error);
            })
        })
    }

    /**
     * 通过图片链接识别用户身份
     * @param imageUrl 用户人脸url
     * @param group 用户所属组
     * @returns {Promise}
     */
    identifyUserFromUrl(imageUrl, group) {
        group = group || defaultDevelop;
        return new Promise((resolve, reject) => {
            NetworkManager.getBase64Image(imageUrl).then(base64Img => {
                _faceClint.identifyUser(group, base64Img, {usertopnum: 5}).then(data => {
                    if (data.error_code === 216618){
                        resolve(Object.assign(data, {result: null}));
                    } else {
                        resolve(data);
                    }
                }, error => {
                    reject(error);
                })
            }, error => {
                reject(error);
            });
        })
    }

    /**
     * 通过图片数据识别用户身份
     * @param image 用户人脸图片
     * @param group 用户所属组
     * @returns {Promise}
     */
    identifyUserFromImage(image, group) {
        group = group || defaultDevelop;
        return new Promise((resolve, reject) => {
            let base64Img = ImageTool.base64FromImageData(image);
            _faceClint.identifyUser(group, base64Img, {usertopnum: 5}).then(data => {
                resolve(data);
            }, error => {
                reject(error);
            })
        });
    }

    /**
     * 通过图片base64识别用户身份
     * @param base64Img 用户人脸图片base64
     * @param group 用户所属组
     * @returns {Promise}
     */
    identifyUserFromBase64Image(base64Img, group) {
        group = group || defaultDevelop;
        return new Promise((resolve, reject) => {
            _faceClint.identifyUser(group, base64Img, {usertopnum: 5}).then(data => {
                resolve(data);
            }, error => {
                reject(error);
            })
        });
    }

    /**
     * 通过用户人脸url注册用户
     * @param id 用户id
     * @param info 用户其他信息
     * @param faceImageUrl 用户人脸url
     * @param group 用户所属组
     * @returns {Promise}
     */
    registerUserFace(id, info, faceImageUrl, group){
        group = group || defaultDevelop;
        return new Promise((resolve, reject) => {
            NetworkManager.getBase64Image(faceImageUrl).then(base64Img => {
                let uid = id;
                let userInfo = info;
                let groupIds = [group];
                _faceClint.addUser(uid, userInfo, groupIds, base64Img).then(data => {
                    resolve(data);
                }, error => {
                    reject(error);
                });
            }, error => {
                reject(error);
            })
        });
    }

    registerUserMutapleFace(id, name, faceImageUrlList){
        if (!(faceImageUrlList instanceof Array)){
            return FaceManager.failPromise('数据类型不正确');
        }
        return new Promise((resolve, reject) => {
            let promiseList = [];
            for (let i = 0; i < faceImageUrlList.length; i++){
                let promose = this.registerUserFace(id, name, faceImageUrlList[i]);
                promiseList.push(promose);
            }
            Promise.all(promiseList).then(data => {
                resolve(data);
            }, error => {
                console.log(error);
                reject(error);
            });
        });
    }

    static failPromise(message){
        return new Promise((resolve, reject) => {
            resolve({data: {}, errorCode: -1, message: message || '失败'})
        })
    }


    getUser(uid) {
        return new Promise((resolve, reject) => {
            _faceClint.getUser(uid).then(data => {
                resolve(data);
            }, error => {
                reject(error);
            })
        });
    }

    static run() {
        // var image = fs.readFileSync(path.resolve(__dirname, '../jiangli.jpeg'));
        // var base64Img = new Buffer(image).toString('base64');
        // _faceClint.detect(base64Img).then(data => {
        //     console.log('获取到数据');
        //     console.log(JSON.stringify(data));
        // }, error => {
        //     console.log('获取事变');
        //     console.log(error);
        // })
        // var uid = '098';
        // var userInfo = '蒋立';
        // var groupIds = ['develop'];

        // _faceClint.addUser(uid, userInfo, groupIds, base64Img).then(data => {
        //     console.log(data);
        // }, error => {
        //     console.log(error);
        // });


        // _faceClint.identifyUser('develop', base64Img, {usertopnum: 5}).then(data => {
        //     console.log(data);
        // }, error => {
        //     console.log(error);
        // })
    }
}


module.exports = FaceManager;